/**
 * 
 */
package com.newture.lxz.generator.component.entity;

import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import com.newture.lxz.generator.component.JavaCodeTemplateRender;
import com.newture.lxz.generator.component.meta.TableMeta;
import com.newture.lxz.util.FileWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author huxiao
 *
 */
public class ColumnConstTemplateRender implements JavaCodeTemplateRender {
	private String outputPackage;
	private String mavenMainJavaPath;
	
	public ColumnConstTemplateRender(String mavenMainJavaPath, String outputPackage) {
		this.mavenMainJavaPath = mavenMainJavaPath;
		this.outputPackage = outputPackage;
	}

	/**
	 * 生成Column字段的静态引用
	 */
	@Override
	public void render(Engine engine, List<TableMeta> tableMetaList) {
		List<Map<String, Object>> targetList = new ArrayList<Map<String, Object>>();

		tableMetaList.forEach((tableMeta) -> {
			String tableName = tableMeta.getTableName();
			String upperTableName = tableName.toUpperCase();

			List<Map<String, String>> targetColumns = new ArrayList<Map<String, String>>();
			tableMeta.getColumnName().forEach((columnName) -> {
				Map<String, String> targetM = new HashMap<String, String>();
				targetM.put("upper", columnName.toUpperCase());
				targetM.put("name", columnName);
				targetColumns.add(targetM);
			});

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("table_name__upper", upperTableName);
			map.put("table_name", tableName);
			map.put("column_list", targetColumns);
			targetList.add(map);
		});

		Kv cond = Kv.by("list", targetList)
				.set("package", outputPackage);

		String templatePath = ColumnConstTemplateRender.class.getResource("").getPath()
				+ "Template__Column.enjoy";
		String template = engine.getTemplate(templatePath).renderToString(cond);

		FileWriter.write(toPath(mavenMainJavaPath, outputPackage), "Column", "java", template);
	}

	public static String toPath(String mavenMainJavaPath, String packageUri) {
		return  mavenMainJavaPath + packageUri.replaceAll("\\.", File.separator);
	}
}
